package com.itmei.threadpool.config;
import java.util.concurrent.RejectedExecutionHandler;
import org.springframework.core.task.TaskDecorator;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @Author itmei
 * @Date 2023/3/16 15:02
 * @description: 线程池对象
 * @Title: ThreadPoolConfig
 * @Package com.itmei.threadpool.config
 */
@Configuration
public class ThreadPoolConfig {
    /**
     * 核心池大小
     */
    private final int corePoolSize = 50;

    /**
     * 最大创建线程数
     */
    private final int maxPoolSize =100;
    /**
     * 线程池维护线程允许的空闲时间 (默认60秒)
     */
    private final int keepAliveSeconds = 300;

    /**
     * 队列最大长度
     */
    private final int queueCapacity = 1000;

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor(){
        ThreadPoolTaskExecutor taskExecutor=new ThreadPoolTaskExecutor();

        taskExecutor.setCorePoolSize(corePoolSize);
        taskExecutor.setMaxPoolSize(maxPoolSize);
        taskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        taskExecutor.setQueueCapacity(queueCapacity);
        // 线程池对拒绝任务(无线程可用)的处理策略
        taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return taskExecutor;
    }
}
